package com.badibadi.mytools;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import org.apache.http.impl.cookie.BasicClientCookie;

import com.badibadi.infos.Results;
import com.badibadi.uniclubber.R;
import com.baidibadi.xutils.DownloadManager;
import com.baidibadi.xutils.DownloadService;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.util.PreferencesCookieStore;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

//xutils 上传图片类
public class XUtils {
	public final static String TAG = "XUtils";
	public static RequestParams params;
	public static Context ct;
	public static Handler handlers;
	// /这下面的是配置属性的
	public static DownloadManager downloadManager;
	public static boolean isFirstLoad = true;// 是否是第一次读取
	// private static PreferencesCookieStore preferencesCookieStore;

	public static android.os.Handler sharehanders = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0:// 多张上传图片
					//    
				try {
					HttpUtils fh = new HttpUtils();
					fh.configSoTimeout(5000000);
					// fh.configRequestRetryCount(3);
					fh.configTimeout(5000000);
					// fh.configSSLSocketFactory(sslSocketFactory);
					downloadManager = DownloadService.getDownloadManager(ct);

					fh.send(HttpRequest.HttpMethod.POST, Constants.BadiUrl
							+ "upload_imgs_pre", params,
							new RequestCallBack<String>() {

								@Override
								public void onStart() {

								}

								@Override
								public void onLoading(long total, long current,
										boolean isUploading) {
									//    
									// + current);
									double count = ((double) ((double) (current) / (double) (total)) * 100);
//									   

									Message msg = new Message();
									msg.what = 1;
									Bundle bun = new Bundle();
									bun.putInt("count", (int) count);
//									   
//											+ total + "isUploading="
//											+ isUploading);
									msg.setData(bun);
									sharehanders.sendMessage(msg);
								};

								@Override
								public void onSuccess(
										ResponseInfo<String> responseInfo) {
									// TODO Auto-generated method stub
									String t = responseInfo.result;
//									   
									Results results = Utils.checkResult_NNN(ct,
											t);
									if (results != null
											&& !results.getRetmsg().equals(
													"null")) {
										Message message = new Message();
										Bundle bundle = new Bundle();
										message.what = 2000;
										bundle.putString("path",
												results.getRetmsg());
										message.setData(bundle);
										handlers.sendMessage(message);
									} else {
										sharehanders.sendEmptyMessage(4);
//										   
									}
								}

								@Override
								public void onFailure(HttpException error,
										String msg) {
									// TODO Auto-generated method stub
//									   
									sharehanders.sendEmptyMessage(4);
								}
							});

				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 1:
				try {
					int count = msg.getData().getInt("count");
					//    
					Utils.setProgress_hen(count);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:// 单张上传
				try {
					HttpUtils fh2 = new HttpUtils();
					fh2.configSoTimeout(5000000);
					// fh.configRequestRetryCount(3);
					fh2.configTimeout(5000000);
					fh2.send(HttpRequest.HttpMethod.POST, Constants.BadiUrl
							+ "upload_img", params,
							new RequestCallBack<String>() {

								@Override
								public void onStart() {

								}

								@Override
								public void onLoading(long total, long current,
										boolean isUploading) {
									//    
									// + current);
									double count = ((double) ((double) (current) / (double) (total)) * 100);
//									   

									Message msg = new Message();
									msg.what = 1;
									Bundle bun = new Bundle();
									bun.putInt("count", (int) count);
//									   
//											+ total + "isUploading="
//											+ isUploading);
									msg.setData(bun);
									sharehanders.sendMessage(msg);
								};

								@Override
								public void onSuccess(
										ResponseInfo<String> responseInfo) {
									// TODO Auto-generated method stub
									String t = responseInfo.result;
//									   
									Results results = Utils.checkResult_NNN(ct,
											t);
									if (results != null
											&& !results.getRetmsg().equals(
													"null")) {
										Message message = new Message();
										Bundle bundle = new Bundle();
										message.what = 2000;
										bundle.putString("path",
												results.getRetmsg());
										message.setData(bundle);
										handlers.sendMessage(message);
									} else {
										sharehanders.sendEmptyMessage(4);
									}
								}

								@Override
								public void onFailure(HttpException error,
										String msg) {
									// TODO Auto-generated method stub
									sharehanders.sendEmptyMessage(4);
								}
							});

				} catch (Exception e) {
					// TODO: handle exception
				}

				// fh2.send(HttpRequest.HttpMethod.POST,Constants.BadiUrl +
				// "upload_img", params,
				// new equestCallBack<String>() {
				// Message message;
				// Bundle bundle;
				//
				// @Override
				// public void onLoading(long count, long current) {
				// // TODO Auto-generated method stub
				// super.onLoading(count, current);
				// Message msg = new Message();
				// msg.what = 1;
				// Bundle bun = new Bundle();
				// bun.putInt("count", (int) count);
				// msg.setData(bun);
				// sharehanders.sendMessage(msg);
				// }
				//
				// @Override
				// public void onSuccess(Object t) {
				// // TODO Auto-generated method stub
				// //    
				// Results results = Utils.checkResult_NNN(ct,
				// (String) t);
				// if (results != null
				// && !results.getRetmsg().equals("null")
				// && results.isRet() == true) {
				// message = new Message();
				// bundle = new Bundle();
				// message.what = 2000;
				// bundle.putString("path",
				// results.getRetmsg());
				// message.setData(bundle);
				// handlers.sendMessage(message);
				// } else {
				// sharehanders.sendEmptyMessage(4);
				// Utils.ExitProgress_hen(ct);
				//    
				// }
				// }
				// });
				break;
			case 3:
				// // 多张上传图片,无逗号
				try {
					HttpUtils fh = new HttpUtils();
					fh.configSoTimeout(5000000);
					// fh.configRequestRetryCount(3);
					fh.configTimeout(5000000);
					downloadManager = DownloadService.getDownloadManager(ct);
					fh.send(HttpRequest.HttpMethod.POST, Constants.BadiUrl
							+ "upload_imgs", params,
							new RequestCallBack<String>() {

								@Override
								public void onStart() {
								}

								@Override
								public void onLoading(long total, long current,
										boolean isUploading) {
									//    
									// + current);
									double count = ((double) ((double) (current) / (double) (total)) * 100);
//									   

									Message msg = new Message();
									msg.what = 1;
									Bundle bun = new Bundle();
									bun.putInt("count", (int) count);
//									   
//											+ total + "isUploading="
//											+ isUploading);
									msg.setData(bun);
									sharehanders.sendMessage(msg);
								};

								@Override
								public void onSuccess(
										ResponseInfo<String> responseInfo) {
									// TODO Auto-generated method stub
									String t = responseInfo.result;
//									   
									Results results = Utils.checkResult_NNN(ct,
											t);
									if (results != null
											&& !results.getRetmsg().equals(
													"null")) {
										Message message = new Message();
										Bundle bundle = new Bundle();
										message.what = 2000;
										bundle.putString("path",
												results.getRetmsg());
										message.setData(bundle);
										handlers.sendMessage(message);
									} else {
										sharehanders.sendEmptyMessage(4);
									}
								}

								@Override
								public void onFailure(HttpException error,
										String msg) {
									// TODO Auto-generated method stub
									sharehanders.sendEmptyMessage(4);
								}
							});

				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 4:// 上传
				try {
					// int count = msg.getData().getInt("count");
					// //    
					// Utils.setProgress_hen(count);
					Utils.ExitProgress_hen(ct);
					Utils.showMessage(ct,
							ct.getResources().getString(R.string.wx2_5));
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
			;
		};
	};

	/**
	 * xutils实现的上传图片
	 * 
	 * @param path
	 * @param context
	 * @param handler
	 */
	public static void UpImg_ceshi_douhaoXUtils(final ArrayList<String> path,
			final Context context, final Handler handler) {
		Utils.showProgress_hen(context);
		ct = context;
		try {
			Utils.showMessage(ct,
					"" + context.getResources().getString(R.string.l_xb46));
		} catch (Exception e) {
			// TODO: handle exception
		}
		params = new RequestParams();

		handlers = handler;
		// File file = new File(ImageTools.ReducePictureQuality(
		// path.get(0),
		// IOUtils.getSaveObjectPath(context,
		// MD5.getMD5(path.get(0)) + ".jpeg")));
		// MyThreadTool.fixedThreadPool.execute(new Runnable() {
		//
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < path.size(); i++) {
			try {
				File file = new File(ImageTools.ReducePictureQuality(
						path.get(i),
						IOUtils.getSaveObjectPath(context,
								MD5.getMD5(path.get(i)) + ".jpeg")));
				// File file = new File(path.get(i));
				if (file.exists()) {
					params.addBodyParameter("file" + i, file);
//					   
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				   
			}

		}
		//    
		sharehanders.sendEmptyMessage(0);
		// }
		// });
		// return backpath;
		// path.remove(0);
		// }
	}

	/**
	 * 上传本地图片（单）
	 * 
	 * @param path
	 *            本地图片地址
	 * @param context
	 *            上下文
	 * @param handler
	 *            拿到服务器返回的图片存储地址的传送者(what=2000)
	 */
	public static void UpImg(String path, final Context context,
			final Handler handler, String uid, final int MSG_SUCCESS) {

		ct = context;
		Utils.showProgress_hen(context);

		Utils.setProgress_henMax(100);
		Utils.setProgress_hen(0);
		params = new RequestParams();
		params.addBodyParameter("uid", uid);
		try {
			Utils.showMessage(ct,
					"" + context.getResources().getString(R.string.l_xb46));
		} catch (Exception e) {
			// TODO: handle exception
		}
//		   
		// File file = new File(ImageTools.ReducePictureQuality(path,
		// IOUtils.getSaveObjectPath(context, MD5.getMD5(path) + ".jpeg")));
		// params.addBodyParameter("info_head", file);
		params.addBodyParameter("info_head", new File(path));
		HttpUtils fh = new HttpUtils();
		fh.configSoTimeout(5000000);
		// fh.configRequestRetryCount(3);
		fh.configTimeout(5000000);
		fh.send(HttpRequest.HttpMethod.POST, Constants.BadiUrl + "upload_img",
				params, new RequestCallBack<String>() {

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// TODO Auto-generated method stub
//								+ "isUploading=" + isUploading);
						double count = ((double) ((double) (current) / (double) (total)) * 100);

						Message msg = new Message();
						msg.what = 1;
						Bundle bun = new Bundle();
						bun.putInt("count", (int) count);
//								+ "isUploading=" + isUploading);
						msg.setData(bun);
						sharehanders.sendMessage(msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						String t = responseInfo.result;
//						LogUtils.d("t=" + t);
						Results results = Utils.checkResult_NNN(context,
								(String) t);

						if (results != null
								&& !results.getRetmsg().equals("null")) {
							Message message = new Message();
							Bundle bundle = new Bundle();
							message.what = MSG_SUCCESS;
							bundle.putString("path", results.getRetmsg());
							bundle.putBoolean("isRet", results.isRet());
							message.setData(bundle);
							handler.sendMessage(message);
						} else {

						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub

					}
				});
		// fh.send(HttpRequest.HttpMethod.POST,Constants.BadiUrl + "upload_img",
		// params,
		// new AjaxCallBack<Object>() {
		// Message message;
		// Bundle bundle;
		//
		// @Override
		// public void onLoading(long count, long current) {
		// // TODO Auto-generated method stub
		// super.onLoading(count, current);
		// }
		//
		// @Override
		// public void onSuccess(Object t) {
		// // TODO Auto-generated method stub
		// Results results = Utils.checkResult_NNN(context,
		// (String) t);
		//
		// if (results != null
		// && !results.getRetmsg().equals("null")) {
		// message = new Message();
		// bundle = new Bundle();
		// message.what = MSG_SUCCESS;
		// bundle.putString("path", results.getRetmsg());
		// bundle.putBoolean("isRet", results.isRet());
		// message.setData(bundle);
		// handler.sendMessage(message);
		// } else {
		//
		// }
		// }
		// });
		// return backpath;
	}

	/**
	 * 上传本地图片（单）
	 * 
	 * @param path
	 *            本地图片地址
	 * @param context
	 *            上下文
	 * @param handler
	 *            拿到服务器返回的图片存储地址的传送者(what=2000)
	 */
	public static void UpData(String uid, String filePath, String fileName,
			final Context context, final Handler handler,
			final int MSG_SUCCESS, final int MSG_fail) {
		ct = context;
		Utils.showProgress_hen(context);

		Utils.setProgress_henMax(100);
		Utils.setProgress_hen(0);
		params = new RequestParams();
		params.addBodyParameter("uid", uid);
//		try {
//			Utils.showMessage(ct,
//					"" + context.getResources().getString(R.string.l_xb46));
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
		// File file = new File(ImageTools.ReducePictureQuality(path,
		// IOUtils.getSaveObjectPath(context, MD5.getMD5(path) + ".jpeg")));
		// params.addBodyParameter("info_head", file);
		params.addBodyParameter("fileName", fileName);
		params.addBodyParameter("info_head",new File(filePath));
		HttpUtils fh = new HttpUtils();
		fh.configSoTimeout(5000000);
		// fh.configRequestRetryCount(3);
		fh.configTimeout(5000000);
		fh.send(HttpRequest.HttpMethod.POST, Constants.BadiUrl_1
				+ "user/uploadExpertFile", params,
				new RequestCallBack<String>() {

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// TODO Auto-generated method stub
//								+ "isUploading=" + isUploading);
						double count = ((double) ((double) (current) / (double) (total)) * 100);

						Message msg = new Message();
						msg.what = 1;
						Bundle bun = new Bundle();
						bun.putInt("count", (int) count);
//								+ "isUploading=" + isUploading);
						msg.setData(bun);
						sharehanders.sendMessage(msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						String t = responseInfo.result;
//						LogUtils.d("t=" + t);
						Results results = Utils.checkResult_NNN(context,
								(String) t);
						if (results != null) {

							if (results.isRet() == true) {
								Message msg = new Message();
								msg.what = MSG_SUCCESS;
								Bundle bun = new Bundle();

								bun.putString("msg", results.getRetmsg());
								msg.setData(bun);
								handler.sendMessage(msg);
							} else {
								handler.sendEmptyMessage(MSG_fail);
							}
						} else {
							handler.sendEmptyMessage(MSG_fail);
						}
						// if (results != null
						// && !results.getRetmsg().equals("null")) {
						// Message message = new Message();
						// Bundle bundle = new Bundle();
						// message.what = MSG_SUCCESS;
						// bundle.putString("path", results.getRetmsg());
						// bundle.putBoolean("isRet", results.isRet());
						// message.setData(bundle);
						// handler.sendMessage(message);
						// } else {
						// handler.sendEmptyMessage(MSG_fail);
						// }
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub

					}
				});
		// fh.send(HttpRequest.HttpMethod.POST,Constants.BadiUrl + "upload_img",
		// params,
		// new AjaxCallBack<Object>() {
		// Message message;
		// Bundle bundle;
		//
		// @Override
		// public void onLoading(long count, long current) {
		// // TODO Auto-generated method stub
		// super.onLoading(count, current);
		// }
		//
		// @Override
		// public void onSuccess(Object t) {
		// // TODO Auto-generated method stub
		// Results results = Utils.checkResult_NNN(context,
		// (String) t);
		//
		// if (results != null
		// && !results.getRetmsg().equals("null")) {
		// message = new Message();
		// bundle = new Bundle();
		// message.what = MSG_SUCCESS;
		// bundle.putString("path", results.getRetmsg());
		// bundle.putBoolean("isRet", results.isRet());
		// message.setData(bundle);
		// handler.sendMessage(message);
		// } else {
		//
		// }
		// }
		// });
		// return backpath;
	}

	// 多张上传，返回值无逗号
	public static void UpImg_ceshi(final ArrayList<String> path,
			final Context context, final Handler handler) {
		ct = context;
		Utils.showProgress_hen(context);
		Utils.setProgress_henMax(100);
		Utils.setProgress_hen(0);
		try {
			Utils.showMessage(ct,
					"" + context.getResources().getString(R.string.l_xb46));
		} catch (Exception e) {
			// TODO: handle exception
		}
		params = new RequestParams();

		handlers = handler;

		handlers = handler;
		// File file = new File(ImageTools.ReducePictureQuality(
		// path.get(0),
		// IOUtils.getSaveObjectPath(context,
		// MD5.getMD5(path.get(0)) + ".jpeg")));

		// MyThreadTool.fixedThreadPool.execute(new Runnable() {
		//
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < path.size(); i++) {
			try {
				File file = new File(ImageTools.ReducePictureQuality(
						path.get(i),
						IOUtils.getSaveObjectPath(context,
								MD5.getMD5(path.get(i)) + ".jpeg")));
				// File file = new File(path.get(i));
				if (file.exists()) {
					params.addBodyParameter("" + i, file);
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				   
			}

		}
		sharehanders.sendEmptyMessage(3);
		// }
		// });

	}

	/**
	 * 上传本地图片（单）
	 * 
	 * @param path
	 *            本地图片地址
	 * @param context
	 *            上下文
	 * @param handler
	 *            拿到服务器返回的图片存储地址的传送者(what=2000)
	 */
	public static void UpImg(final String path, final Context context,
			final Handler handler) {
		// Utils.showPrgress_Noclose(context);
		ct = context;
		// Utils.showPrgress(context);
		Utils.showProgress_hen(context);
		Utils.setProgress_henMax(100);
		Utils.setProgress_hen(0);
		try {
			Utils.showMessage(ct,
					"" + context.getResources().getString(R.string.l_xb46));
		} catch (Exception e) {
			// TODO: handle exception
		}
		params = new RequestParams();
		ct = context;
		handlers = handler;
		// MyThreadTool.fixedThreadPool.execute(new Runnable() {
		//
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		try {
			// File file = new File(ImageTools.ReducePictureQuality(
			// path,
			// IOUtils.getSaveObjectPath(context, MD5.getMD5(path)
			// + ".jpeg")));
			File file = new File(path);
			if (file.exists()) {
				params.addBodyParameter("info_head", file);
			} else {
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			   
		}
		// }
		// });
		sharehanders.sendEmptyMessage(2);
		// return backpath;
	}

	public static enum HttpMethod {
		GET("GET"), POST("POST"), PUT("PUT"), HEAD("HEAD"), MOVE("MOVE"), COPY(
				"COPY"), DELETE("DELETE"), OPTIONS("OPTIONS"), TRACE("TRACE"), CONNECT(
				"CONNECT");

		private final String value;

		HttpMethod(String value) {
			this.value = value;
		}

		@Override
		public String toString() {
			return this.value;
		}
	}
}
